package com.lzxuni.modules.organization.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.modules.common.entity.Tree;
import com.lzxuni.modules.organization.entity.Company;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.mapper.CompanyMapper;
import com.lzxuni.modules.organization.service.BankService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 机构单位表 服务实现类
 * </p>
 *
 * @author 孙志强
 * @since 2018-12-05
 */
@Service
public class BankServiceImpl extends ServiceImpl<CompanyMapper, Company> implements BankService {

	@Override
	public List<Tree> getTree(String parentId) {
		List<Tree> list = baseMapper.queryListByParentId(parentId);

		getTreeDg(list);
		return list;
	}

	@Override
	public Boolean insert(User user, Company company) {
		if (user != null) {
			company.setCreateUserId(user.getUserId());
			company.setCreateUsername(user.getUsername());
		}
		if (StringUtils.isEmpty(company.getParentId())) {
			company.setParentId("0");
		}else{
			if(company.getParentId().equals("-1")){
				company.setParentId("0");
			}
		}

		return this.save(company);
	}

	@Override
	public Boolean update(User user, Company company) {
		if (user != null) {
			company.setModifyUserId(user.getUserId());
			company.setModifyUsername(user.getUsername());
		}
		if (StringUtils.isEmpty(company.getParentId())) {
			company.setParentId("0");
		}else{
			if(company.getParentId().equals("-1")){
				company.setParentId("0");
			}
		}
		return this.updateById(company);
	}

	@Override
	public Object getMap(String ver) {
		List<Company> list = this.list();
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();

		for (int i = 0; i < list.size(); i++) {
			HashMap<String, Object> map2 = new HashMap<>();
			map2.put("parentId", list.get(i).getParentId());
			map2.put("name", list.get(i).getFullName());

			map1.put(list.get(i).getCompanyId(), map2);
		}
		map.put("data", map1);
		map.put("ver", "123");
		return map;
	}


	/*私有方法区域*/
	private void getTreeDg(List<Tree> ztreeList) {
		for (int i = 0; i < ztreeList.size(); i++) {
			Tree tree = ztreeList.get(i);
			List<Tree> treeList = baseMapper.queryListByParentId(tree.getId());
			if (treeList != null && treeList.size() > 0) {
				tree.setChildNodes(treeList);
				tree.setHasChildren(true);
				tree.setIsexpand(true);
			}
			getTreeDg(treeList);
		}
	}
}
